let maxNo = null;
let lock = true;

$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange, useBeforeClick, useAction }) {
    window._totalNum = 0;
    console.log(page, "page is ready");
    console.log($NG.getPageUI());
    console.log($NG.getPageState());

    window._list = [];

    var mstform = $NG.getCmpApi("p_form_equipment_list");
    var dgrid1 = $NG.getCmpApi("p_form_equipment_list_d");
    var dgrid2 = $NG.getCmpApi("p_form_equipment_list_impl");
    var dgrid3 = $NG.getCmpApi("p_form_equipment_list_svc");
    var dgrid4 = $NG.getCmpApi("p_form_equipment_list_rd");
    const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_equipment_list_d");

    // 合同清单 重复值map
    const duplicateMap = new Map();
    const seenItemNo = new Set(); // 记录哪些item_no已经赋过值

    const pageOtype = ["add", "edit", "copy"].includes(page.oType);

    if (mstform) {
        mstformUpdateUI();
        if (pageOtype) {
            console.log("page.oType" + page.oType);
            cntMFilter();
            cntDFilter();
            if (mstform.getItem("phid_pc").getValue()) {
                getPtInfoByPhid();
                getCntCount("p_form_equipment_list", "u_cnt", getCntMInfoByPhid, danjvchaxun);
            }
        }
    }

    useAction("clickHighlight")(function (e) {
        openDJ();
    });
      async function getSbqdAmtInfo() {
    let lock = true;
    const data = $NG.getCmpApi("grid").getSelectedData()[0].phid;
    if (data) {
      await $NG.execServer("getSbqdAmtInfo", { phid: data }, (res) => {
        console.log(`设备清单是否可以审核`, res);
        if (res.count == 0) return;
        const _data = JSON.parse(res.data)[0].extendObjects;
        if (!_data.impl || !_data.svc || !_data.rd) {
          lock = false;
        }
      });
    }
    return lock;
  }
    // 深化校验
      useBeforeClick(async () => {
    if (page.isList) {
      const lock = await getSbqdAmtInfo();
      if (!lock) {
        $NG.alert("该设备清单的实施、服务、二开费用有其一为空，不予审核!");
      }
      return lock;
    } else {
      // 非列表页面
      console.log(`审核按钮被点击`);
      const arr2 = dgrid2.getRows().length;
      const arr3 = dgrid3.getRows().length;
      const arr4 = dgrid4.getRows().length;
      if (!arr2 || !arr3 || !arr4) {
        $NG.alert("实施费用、服务费用、二开费用单，有不存在预算单，不予审核！");
        return false;
      }
    }
  }, "check");
    ////////////////////////////////////////////////////////////--init--////////////////////////////////////////////////////////////

    //页面条件
    if (page.oType == "add" || page.oType == "edit" || page.oType == "copy") {
        let result = checkImpdataStatus();
        if (result.valid) {
            // 没有未审核单据，继续其他操作
        } else {
            // 有未审核单据，处理逻辑
            console.log(result.message); // 可以使用返回的提示信息
        }
    }

    ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////

    let editbar = $NG.getPageUI().find((item) => item.name === "editbar");
    let toolbar1 = editbar?.children.find((item) => item.name === "p_form_equipment_list_d");

    if (toolbar1 && Array.isArray(toolbar1.children)) {
        let newButton = {
            id: "user_insert",
            text: "插行",
            iconCls: "InsertRowBelowOutlined",
        };

        // 找到 `addrow` 按钮的索引
        let addrowIndex = toolbar1.children.findIndex((btn) => btn.name === "addrow");

        // 在 `addrow` 按钮后插入新按钮
        if (addrowIndex !== -1) {
            toolbar1.children.splice(addrowIndex + 1, 0, newButton);
            // console.log("新按钮已插入", toolbar1.children);
        } else {
            console.warn("未找到 addrow 按钮");
        }
    } else {
        console.warn("未找到工具栏 p_form_equipment_list_d");
    }

    // // 增加插行
    // toolbar_dgrid.insert({
    //   id: "user_insert",
    //   text: "插行",
    //   iconCls: "icon-InsertRow",
    // });

    // 增加匹配物料
    if (page.oType != "view") {
        toolbar_dgrid.insert({
            id: "user_match",
            text: "匹配物料",
            iconCls: "icon-InsertRow",
        });
    }

    toolbar_dgrid.insert({
        id: "template_download",
        text: "模板下载",
        iconCls: "icon-InsertRow",
    });

    toolbar_dgrid.insert({
        id: "openMateil",
        text: "跳转标准物料",
        iconCls: "icon-InsertRow",
    });
    useClick(() => {
        const keys = [
            ["u_sub_item", "u_sub_name", "u_sub_item_msunit", "u_sub_ggxh", "u_sub_item_category"],
            ["u_pur_item", "u_pur_name", "u_pur_item_msunit", "u_pur_ggxh", "u_pur_item_category"],
            ["u_self_item", "u_self_name", "u_self_item_msunit", "u_self_ggxh", "u_self_item_category"],
        ];
        const boolkey = ["nfb_bz", "ncg_bz", "nzz_bz"];
        const arr = dgrid1.getRows();
        ToWlApply(arr, keys, boolkey);
    }, "openMateil");

    let reqLock = 0;
    let jindutiaoLock = 0;
    useClick(function ({ args }) {
        $NG.message(`正在匹配 0% 请耐心等待，勿操作`);
        $NG.message(`正在匹配 5% 请耐心等待，勿操作`);
        window.endNum = 0;
        window.newNum = 0;
        window._list = [];

        // jindutiaoLock = setInterval(() => {
        //   window._jindu = window.endNum / dgrid1.getRows().length;
        //   $NG.message(`正在匹配 ${window._jindu.toFixed(2) * 100}%`);
        // }, 2500);

        getItemData(null, false);
        reqLock = setInterval(() => {
            if (window.endNum == window.newNum) {
                clearInterval(jindutiaoLock);
                console.log(`start   `, { ...window._list[0] });
                let _temp = removeDuplicatesByKeys(window._list);
                $NG.message(`正在匹配 90% 请等待提示完成后继续操作`);
                getWlRequest(_temp);
                console.log(window._list);
                console.log("发送完成", _temp);
                clearInterval(reqLock);
            } else {
                window.endNum = window.newNum;
            }
        }, 1000);
    }, "user_match");

    useBeforeClick(async () => {
        var dgrid = $NG.getCmpApi('p_form_equipment_list_d');
        const ds = dgrid.getRows()
        const type = []
        const task = []
        ds.forEach((item, index) => {
            if (item.u_self_item && item.checked) {
                const pro = new Promise((reot) => {
                    $NG.execServer("getItemNameIsAppType", { phid: item.u_self_item }, function (res) {
                        if (res.count == 0) return
                        const data = JSON.parse(res.data)[0].extendObjects
                        if (data.user_item_type == '2') {
                            type.push(index)
                        }
                        reot()
                    })

                })
                task.push(pro)
            }
        })
        await Promise.all(task)
        console.log(`软件物料`, type);
        let lock = true
        if (type.length != 0) {
            lock = await $NG.confirm('选中数据包含收入类型为 “软件收入” 的明细，继续下推将自动过滤掉相关明细，反之则手动修改！')
        }
        if (lock) {
            const arrs = dgrid.getRows()
            type.forEach(item => {
                arrs[item].checked = false
                dgrid.updateRow(arrs[item])
            })
            let num = arrs.reduce((value, item) => {
                if (item.checked) {
                    value += 1
                }
                return value
            }, 0)
            if (num == 0) {
                $NG.alert("除去软件类型物料，您没有选中任何行~")
                return false
            }
            return true
        } else { return false }
    }, "imp_push")

    useClick(async function ({ args }) {
        insertClick();
    }, "user_insert");

    useClick(async function ({ args }) {
        // 获取项目选择的值
        const SelectionValue1 = mstform.getItem("u_pc_no").getValue(); // 动态获取的项目选择值
        const SelectionValue2 = mstform.getItem("u_cnt_no").getText(); // 动态获取的合同选择值

        // 构造 URL 参数
        const url = window.location.href;
        const protocol = $NG.split(url, "/")[0]; // 协议类型
        const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
        const url_path = "/report/index.html#/tableDesign/TableManager/preview"; // 路径
        const query_params = new URLSearchParams({
            // preview: 1,
            rep_id: "8570000000000006",
            name: "",
            defaultSheet: 0,
            AppTitle: "",
            menucode: "79429a86-526a-403c-9862-cb3503184d68",
            linkParams: JSON.stringify([
                {
                    dataSetId: "8570000000000021",
                    operator: "like",
                    paramKey: "pt_no",
                    paramValue: SelectionValue1,
                    paramValueSource: "user_input",
                },
                {
                    dataSetId: "8570000000000010",
                    operator: "like",
                    paramKey: "pcm_no",
                    paramValue: SelectionValue2,
                    paramValueSource: "user_input",
                },
            ]),
        }).toString(); // 使用 URLSearchParams 来构造查询参数

        // 打开报表并传递参数
        $NG.open(`${protocol}//${url_domain}${url_path}?${query_params}`, { AppTitle: "模板下载" });
    }, "template_download");


    // 跳转模板导入
    toMbIn("p_form_equipment_list_d", "to_template")
    function toMbIn(tableName, btnId) {
        const toolbar_dgrid = $NG.getCmpApi("toolbar_" + tableName)
        toolbar_dgrid.insert({
            id: btnId,
            text: "导出",
            iconCls: "icon-InsertRow",
        });
        useClick(async function ({ args }) {
            // 获取项目选择的值
            const phid = mstform.getValues().phid

            // 构造 URL 参数
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = "/report/index.html#/tableDesign/TableManager/preview"; // 路径
            const query_params = new URLSearchParams({
                // preview: 1,
                rep_id: "8570000000000014",
                name: "",
                defaultSheet: 0,
                AppTitle: "",
                menucode: "79429a86-526a-403c-9862-cb3503184d68",
                linkParams: JSON.stringify([
                    {
                        dataSetId: "8570000000000034",
                        operator: "like",
                        paramKey: "phid",
                        paramValue: phid,
                        paramValueSource: "user_input",
                    }
                ]),
            }).toString(); // 使用 URLSearchParams 来构造查询参数

            // 打开报表并传递参数
            $NG.open(`${protocol}//${url_domain}${url_path}?${query_params}`, { AppTitle: "模板下载" });
        }, btnId);
    }

    // 查询事业部总经理
    getCzyisOrgzjl()
    function getCzyisOrgzjl() {
        $NG.execServer("getCzyisOrgzjl", { userno: $NG.getUser().logid }, (res) => {
            if (res.count == 0) return
            const keys = ["u_unforeseeable_ze", "u_unforeseeable_fbys", "u_unforeseeable_zdys", "u_unforeseeable_zefs",
                "u_unforeseeable_zdfs", "u_unforeseeable_fbfs", "u_unforeseeable_syfb", "u_unforeseeable_syzd"]
            keys.forEach((item) => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_equipment_list[item].setProps({
                        hidden: false
                    })
                })
            })

        })
    }
    try {
        let u_cnt_type = 0
        let viewLock = 0
        let u_cnt_type_lock = setInterval(() => {
            if (!mstform) {
                viewLock++
            }
            if (viewLock == 10) {
                clearInterval(u_cnt_type_lock)
            }
            if (mstform.getItem("u_cnt_type").getValue() != u_cnt_type) {
                hideHeadkey()
                u_cnt_type = mstform.getItem("u_cnt_type").getValue()
            }
        }, 500)
    } catch (e) {
        console.error(`try 隐藏合同总含税金额异常`, e);
    }


    function hideHeadkey() {
        const u_cnt_type = mstform.getItem("u_cnt_type").getValue()
        console.log(`当前隐藏情况`, (u_cnt_type == 8570000000000002));
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_equipment_list.u_total_cnt_amt_vat.setProps({
                hidden: (u_cnt_type == 8570000000000002)
            })
        })
    }

    // toolbar_dgrid.insert({
    //   id: "imp_updown",
    //   text: "选中后点击穿透到定价申请",
    //   iconCls: "icon-InsertRow",
    // });
    // // 选中后点击穿透到定价申请
    // // 穿透到报表，目前还未做
    // useAction("onClick")(() => {
    //   // $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?id=${dgrid2.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000034&isSso=0`, { AppTitle: "实施费用预算" });
    // }, "imp_updown");

    //按钮点击前事件
    useBeforeClick(async ({ args }) => {
        console.log(`保存`);
        console.log(lock);
        let subcheck = true;
        let subItemCheck = true;
        let subItemArr = [];
        let isReat = [[],[],[]]
        let subArr = [];
        let purcheck = true;
        let purItemCheck = true;
        let purArr = [];
        let purItemArr = [];
        let selfcheck = true;
        let selfItemCheck = true;
        let selfArr = [];
        let selfItemArr = [];

        let result = checkImpdataStatus();
        if (result.valid) {
            // 没有未审核单据，继续其他操作
        } else {
            // 有未审核单据，处理逻辑
            console.log(result.message); // 可以使用返回的提示信息
            return false;
        }

        if ($NG.getPageState().data.p_form_equipment_list.phid_schemeid == 8570000000000329) {
            let u_ad_total_amt = mstform.getItem("u_ad_total_amt").getValue();
            let u_total_cost_amt = mstform.getItem("u_total_cost_amt").getValue();
            if (u_total_cost_amt > u_ad_total_amt) {
                $NG.alert(`项目总未税成本 ${u_total_cost_amt} 超过提前施工总投入${u_ad_total_amt}`);
                return false;
            }
            let u_ad_material_amt = mstform.getItem("u_ad_material_amt").getValue();
            let u_pur_cost_amt = mstform.getItem("u_pur_cost_amt").getValue();
            if (u_pur_cost_amt > u_ad_material_amt) {
                $NG.alert(`拟采购成本未税 ${u_pur_cost_amt} 提前施工材料投入${u_ad_material_amt}`);
                return false;
            }
            let u_ad_engineering_amt = mstform.getItem("u_ad_engineering_amt").getValue();
            let u_sub_cost_amt = mstform.getItem("u_sub_cost_amt").getValue();
            if (u_sub_cost_amt > u_ad_engineering_amt) {
                $NG.alert(`拟分包成本未税 ${u_sub_cost_amt} 提前施工工程投入${u_ad_engineering_amt}`);
                return false;
            }
            let u_self_owned_cost = mstform.getItem("u_self_owned_cost").getValue();
            let u_self_cost = mstform.getItem("u_self_cost").getValue();
            if (u_self_cost > u_self_owned_cost) {
                $NG.alert(`拟自制成本未税 ${u_self_cost} 提前施工自主产品投入${u_self_owned_cost}`);
                return false;
            }
            let u_implement_cost = mstform.getItem("u_implement_cost").getValue();
            let u_implement_amt = mstform.getItem("u_implement_amt").getValue();
            if (u_implement_amt > u_implement_cost) {
                $NG.alert(`实施费 ${u_implement_amt} 提前施工实施费用投入${u_implement_cost}`);
                return false;
            }
        }

        await dgrid1.getRows().forEach((item, index) => {
            // 获取物料信息
            // getItemDataByPhid(items);
            if (item.u_pur_name && item.u_pur_name.replaceAll(" ", "") != "") {
                if (!item.u_pur_item_category || !item.u_pur_item_msunit || !item.u_pur_ggxh) {
                    purArr.push(index + 1);
                    purcheck = false;
                }
                
            }
            if (!item.u_pur_item && item.u_pur_name && item.u_pur_item_msunit && item.u_pur_ggxh) {
                purItemArr.push(index + 1);
                purItemCheck = false;
            } else {
                    if(item.u_pur_tax_rate == 0){
                    isReat[1].push(index + 1)
                }
            }

            if (item.u_sub_name && item.u_sub_name.replaceAll(" ", "") != "") {
                if (!item.u_sub_item_category || !item.u_sub_item_msunit || !item.u_sub_ggxh) {
                    subcheck = false;
                    subArr.push(index + 1);
                }
            }
            if (!item.u_sub_item && item.u_sub_name && item.u_sub_item_msunit && item.u_sub_ggxh) {
                subItemArr.push(index + 1);
                subItemCheck = false;
            } else {
                if(item.u_sub_tax_rate == 0){
                    isReat[0].push(index + 1)
                }
            }
            // if (item.u_self_name && item.u_self_name.replaceAll(" ", "") != "") {
            //     if (!item.u_self_item_category || !item.u_self_item_msunit || !item.u_self_ggxh) {
            //         selfcheck = false;
            //         selfArr.push(index + 1);
            //     }
            // }
            // if (!item.u_self_item && item.u_self_name && item.u_self_item_msunit && item.u_self_ggxh) {
            //     selfItemArr.push(index + 1);
            //     selfItemCheck = false;
            // }
            if (item.u_self_item) {
                if(item.u_self_tax_rate == 0){
                    isReat[2].push(index + 1)
                }
            }
        });
        // 查看是否存在清单
        // 汇总错误信息
        let errorMessages = [];
        if (!purItemCheck) {
            errorMessages.push(`设备清单明细第 ${purItemArr.join("、")} 行 拟采购项未匹配成功，请先匹配或者先进行标准物料申请`);
        }
        if (!purcheck) {
            errorMessages.push(`设备清单明细第 ${purArr.join("、")} 行 拟采购项分类、计量单位、规格型号数据不全`);
        }
        if (!subItemCheck) {
            errorMessages.push(`设备清单明细第 ${subItemArr.join("、")} 行 拟分包项未匹配成功，请先匹配`);
        }
        if (!subcheck) {
            errorMessages.push(`设备清单明细第 ${subArr.join("、")} 行 拟分包分类、计量单位、规格型号数据不全`);
        }
        // if (!selfItemCheck) {
        //     errorMessages.push(`设备清单明细第 ${selfItemArr.join("、")} 行 拟自制项未匹配成功，请先匹配`);
        // }
        // if (!selfcheck) {
        //     errorMessages.push(`设备清单明细第 ${selfArr.join("、")} 行 拟自制分类、计量单位、规格型号数据不全`);
        // }
        let lock_rate = isReat.reduce((value,item,index)=>{
            if(item.length != 0){
                switch(index){
                    case 0:
                        value += "拟分包第"+item.join(",")+"行"
                        break
                    case 1:
                        value += "拟采购第"+item.join(",")+"行"
                        break
                    case 2:
                        value += "拟自制第"+item.join(",")+"行" 
                        break
                }
            }
            if(index == 2 && value != ""){
                value += "税率不能为0！"
            }
            return value
        },"")
        console.log(`当前税率值`,isReat);

        if(lock_rate != ""){
            $NG.alert(lock_rate)
            return false
        }
        // 如果有错误信息，则弹出提示框
        if (errorMessages.length > 0) {
            $NG.alert(errorMessages.join("\n"));
            return false;
        }

        let u_total_cnt_amt_vat = mstform.getItem("u_total_cnt_amt_vat").getValue().toFixed(2); //合同总额
        let u_cnt_amt_vat = mstform.getItem("u_cnt_amt_vat").getValue().toFixed(2); //清单合同总额
        if (u_total_cnt_amt_vat !== u_cnt_amt_vat&&(mstform.getItem("u_cnt_type").getValue() != 8570000000000002)) {
          $NG.message(`清单合同金额 ${u_cnt_amt_vat} 与合同总金额 ${u_total_cnt_amt_vat} 不一致， 请检查设备清单中合同金额是否正确`);
          // return false;
        }

        let exit = true;
        console.log(`保存设置1`, lock);

        if (!lock) {
            exit = false;
            $NG.alert("当前项目已存在设备清单!");
        }

        return exit;
    }, "save");

    // 单击逻辑
    useClick(function ({ args }) {
        console.log(args, "1XXX1???");
        useDataFun("ArrData", "clear");
        useDataFun("ArrData", "save", dgrid1.getRows());
    }, "imp_push");
    useClick(async function ({ args }) {
        var data = {
            LinkRep_tarSheets: "0",
            LinkRep_tarCells: "b1",
            LinkRep_srcParas: `${mstform.getItem("u_cnt").getValue()}`,
        };
        var replinkdata = encodeURIComponent(JSON.stringify(data));
        const url = window.location.href;
        const arr = $NG.split(url, "/");
        const protocol = arr[0]; // 协议类型
        const url_domain = arr[2];
        const url_path = `/RW/DesignFrame/ReportView?rep_src=0&rep_code=202502100002&replink=true&datavaluetype=cell&replinkdata=${replinkdata}`;
        $NG.open(`${protocol}//${url_domain}${url_path}`, { AppTitle: "模板下载" });
    }, "template_download2");

    ////////////////////////////////////////////////////////////--mstform

    //监听字段：项目
    useValuesChange(({ args }) => {
        let result = checkImpdataStatus();
        if (result.valid) {
            // 没有未审核单据，继续其他操作
        } else {
            // 有未审核单据，处理逻辑
            console.log(result.message); // 可以使用返回的提示信息
        }
        cntMFilter();

        getPtInfoByPhid();
        getCntCount("p_form_equipment_list", "u_cnt", getCntMInfoByPhid, danjvchaxun);
    }, "p_form_equipment_list.phid_pc");

    // 监听字段：合同
    useValuesChange(({ args }) => {
        getCntMInfoByPhid();
    }, "p_form_equipment_list.u_cnt");

    // 监听字段：中标服务费
    useValuesChange(({ args }) => {
        sumGridToForm();
    }, "p_form_equipment_list.u_win_bid_svc_amt");
    //中标商机字段监听
    useValuesChange(({ args }) => {
        getAdConstructionOpp();
    }, "p_form_equipment_list.u_opportunity_obj");

    //自动获取设备清单的实施费用和服务费用
    if (page.oType == page.OType.Add || page.oType == page.OType.Edit) {
        var dgrid2 = $NG.getCmpApi("p_form_equipment_list_impl");
        var dgrid3 = $NG.getCmpApi("p_form_equipment_list_svc");
        var dgrid4 = $NG.getCmpApi("p_form_equipment_list_rd");

        useValuesChange(({ args }) => {
            danjvchaxun();
        }, "p_form_equipment_list.u_cnt");
    }

    ////////////////////////////////////////////////////////////--dgrid1

    if (dgrid1) {
        dgrid1UpdateUI();
        // handleClick();

        registerCalcGroup({
            dataKey: "p_form_equipment_list_d",
            qtyField: "u_pur_qty",
            taxRate: "u_pur_tax_rate",
            prcField: "u_pur_prc",
            prcVatField: "u_pur_prc_vat",
            amtField: "u_pur_cost",
            amtVatField: "u_pur_cost_vat",
        });

        registerCalcGroup({
            dataKey: "p_form_equipment_list_d",
            qtyField: "u_sub_qty",
            taxRate: "u_sub_tax_rate",
            prcField: "u_sub_prc",
            prcVatField: "u_sub_prc_vat",
            amtField: "u_sub_cost",
            amtVatField: "u_sub_cost_vat",
        });

        registerCalcGroup({
            dataKey: "p_form_equipment_list_d",
            qtyField: "u_self_qty",
            taxRate: "u_self_tax_rate",
            prcField: "u_self_prc",
            prcVatField: "u_self_prc_vat",
            amtField: "u_self_cost",
            amtVatField: "u_self_cost_vat",
        });

        // 选择拟分包项
        useDataIndexChange(({ args, instance }) => {
            console.log(`监听 p_form_equipment_list_d u_sub_item`, args);
            const items = args[0];
            getSubItemDataByPhid(items);
        }, "p_form_equipment_list_d.u_sub_item");

        // 选择拟采购项
        useDataIndexChange(({ args, instance }) => {
            console.log(`监听 p_form_equipment_list_d u_pur_item`, args);
            const items = args[0];
            getPurItemDataByPhid(items);
        }, "p_form_equipment_list_d.u_pur_item");

        // 选择拟自主项
        useDataIndexChange(({ args, instance }) => {
            console.log(`监听 p_form_equipment_list_d u_self_item`, args);
            const items = args[0];
            getSelfItemDataByPhid(items);
        }, "p_form_equipment_list_d.u_self_item");

        // 监听明细单行：dgrid1
        useUpdateRow(async ({ args, table }) => {
            console.log(`触发监听:useUpdateRow`);
            const items = args[0];
            await getItemDataByName(items);
            table.updateRow(items);
        }, "p_form_equipment_list_d");

        // 监听全部表体：dgrid1
        useUpdateRows(({ args, table }) => {
            console.log(`触发监听:useUpdateRows动作`, args);

            seenItemNo.clear(); // 🚿 每次开始处理前都要清空一次

            const rows = args[0];
            const clearList = {}; // 用于存储清单编号

            let clearCodeCounter = 1; // 清单编码计数器，从 1 开始
            let lock = false; //要刷新吗

            //用来存储重复数据判定
            let dataIsDbclick = [];
            rows.forEach(async (items, index) => {
                // 计算设备清单明细
                caculatedgrid1(items);

                // getItemDataByName(items);

                //根据导入的合同编码匹配合同清单
                getCntDInfoByNo(items, duplicateMap);
                if (!items.u_state) {
                    items.u_state = "normal";
                }

                //1、自动生成设备清单
                const { u_equipment_list_name, u_model } = items;
                const key = `${u_equipment_list_name}_${u_model}`; // 根据名称和型号生成唯一标识符

                if (!clearList[key]) {
                    // 如果清单编号不存在，则生成新的编号
                    const serialPart = String(clearCodeCounter).padStart(4, "0"); // 将计数器格式化为4位
                    clearList[key] = "A" + serialPart; // 生成清单编号
                    clearCodeCounter++;
                }

                if (!/^\d{14}$/.test(items.u_equipment_list_no)) {
                    items.u_equipment_list_no = autoCreateNo(index + 1);
                }

                //判断是否合同清单重复
                if (dataIsDbclick.indexOf(String(items.u_cnt_item)) == -1) {
                    dataIsDbclick.push(String(items.u_cnt_item));
                    // console.log("不包括", items.u_cnt_item, dataIsDbclick);
                } else {
                    // 已有当前清单
                    items.u_cnt_amt == null;
                }
                // console.log(dataIsDbclick);
                dgrid1.refreshView();
            });
            sumGridToForm();
            if (lock) {
                dgrid1.refreshView();
            }
        }, "p_form_equipment_list_d");

        // 监听主表字段：合同
        useDataIndexChange(async ({ args, instance }) => {
            console.log(`触发监听:useDataIndexChange`);
            const record = args[0];
            const details = dgrid1.getData();
            if (record.u_cnt_item) {
                await detectUniqueContractList(details);
                await getCntDInfoByPhid(record, duplicateMap);
            }
            sumGridToForm();
        }, "p_form_equipment_list_d.u_cnt_item");
    }

    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////

    if (dgrid2) {
        var dgrid2_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_impl");
        dgrid2_toolbar.hideButton("addrow");
        dgrid2_toolbar.hideButton("deleterow");
        dgrid2_toolbar.hideButton("imp");
        dgrid2_toolbar.hideButton("import");
        dgrid2_toolbar.hideButton("attachment");
        dgrid2_toolbar.insert({
            id: "dgrid2Click",
            text: "选中后点击穿透到预算单",
            iconCls: "icon-New",
        });
        useAction("onClick")(() => {
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = `/react/index.html#/customform/detail?id=${dgrid2.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000034&isSso=0`; // 路径
            $NG.open(`${protocol}//${url_domain}${url_path}`, { AppTitle: "实施费用预算" });
        }, "dgrid2Click");

        useUpdateRows(({ args }) => {
            const rows = args[0];
            sumGridToForm();
        }, "p_form_equipment_list_impl");
        $NG.updateUI((updater) => {
            const fields = ["u_source_phid", "u_data_status"];
            fields.forEach((field) => {
                updater.editGrid.p_form_equipment_list_impl[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
    }

    ////////////////////////////////////////////////////////////--dgrid3--////////////////////////////////////////////////////////////

    if (dgrid3) {
        var dgrid3_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_svc");
        dgrid3_toolbar.hideButton("addrow");
        dgrid3_toolbar.hideButton("deleterow");
        dgrid3_toolbar.hideButton("imp");
        dgrid3_toolbar.hideButton("import");
        dgrid3_toolbar.hideButton("attachment");
        dgrid3_toolbar.insert({
            id: "dgrid3Click",
            text: "选中后点击穿透到预算单",
            iconCls: "icon-New",
        });
        useAction("onClick")(() => {
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = `/react/index.html#/customform/detail?id=${dgrid3.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000035&isSso=0`; // 路径
            $NG.open(`${protocol}//${url_domain}${url_path}`, { AppTitle: "服务费用预算" });
        }, "dgrid3Click");
        useUpdateRows(({ args }) => {
            const rows = args[0];
            sumGridToForm();
        }, "p_form_equipment_list_svc");
        $NG.updateUI((updater) => {
            const fields = ["u_source_phid", "u_data_status"];
            fields.forEach((field) => {
                updater.editGrid.p_form_equipment_list_svc[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
    }
    ////////////////////////////////////////////////////////////--dgrid4--////////////////////////////////////////////////////////////

    if (dgrid4) {
        var dgrid4_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_rd");
        dgrid4_toolbar.hideButton("addrow");
        dgrid4_toolbar.hideButton("deleterow");
        dgrid4_toolbar.hideButton("imp");
        dgrid4_toolbar.hideButton("import");
        dgrid4_toolbar.hideButton("attachment");
        dgrid4_toolbar.insert({
            id: "dgrid4Click",
            text: "选中后点击穿透到预算单",
            iconCls: "icon-New",
        });
        useAction("onClick")(() => {
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = `/react/index.html#/customform/detail?id=${dgrid4.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000129&isSso=0`; // 路径
            $NG.open(`${protocol}//${url_domain}${url_path}`, { AppTitle: "二开费用预算" });
        }, "dgrid4Click");
        useUpdateRows(({ args }) => {
            const rows = args[0];
            sumGridToForm();
        }, "p_form_equipment_list_rd");
        $NG.updateUI((updater) => {
            const fields = ["u_source_phid", "u_data_status"];
            fields.forEach((field) => {
                updater.editGrid.p_form_equipment_list_rd[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
    }

    //////////////////////////////////////////////////-- function--//////////////////////////////////////////////////

    function mstformUpdateUI(params) {
        // 字段隐藏
        const _arrHideM = [
            // "u_total_cost_amt_vat",
            // "u_total_cost_change",
            // "u_pur_cost_vat",
            // "u_sub_cost",
            // "u_self_cost_vat",
            // "u_pur_reduction_cost",
        ];
        _arrHideM.forEach((field) => {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_equipment_list[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
        if ($NG.getPageState().data?.p_form_equipment_list?.phid_schemeid == 8570000000000329) {
            $NG.updateUI((updater) => {
                const fields = ["u_cnt", "u_cnt_no", "u_invoice_type", "u_cnt_type", "u_cnt_amt", "u_total_cnt_amt_vat"];
                fields.forEach((field) => {
                    updater.fieldSetForm.p_form_equipment_list[field].setProps({
                        required: false, //必输
                        disabled: true, //只读
                        // hidden: true, //隐藏
                    });
                });
            });
        } else {
            $NG.updateUI((updater) => {
                const fields = ["u_ad_total_amt", "u_ad_material_amt", "u_ad_engineering_amt", "u_self_owned_cost", "u_implement_cost", "u_opportunity_obj_no", "u_opportunity_obj", "u_bid_winning_date", "u_opp_amt", "u_winning_bid_amt"];
                fields.forEach((field) => {
                    updater.fieldSetForm.p_form_equipment_list[field].setProps({
                        hidden: true, //隐藏
                        required: false, //必输
                        disabled: true, //只读
                    });
                });
            });
        }
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_list.u_cnt_no.setProps({
                onDoubleClick() {
                    var u_cnt_phid = $NG.getCmpApi("p_form_equipment_list").getItem("u_cnt_no").getValue();
                    if (u_cnt_phid) {
                        // 弹出确认框
                        // var isConfirmed = $NG.confirm("您确定要跳转到合同信息吗？");
                        // if (isConfirmed) {
                        const url = window.location.href;
                        const protocol = $NG.split(url, "/")[0]; // 协议类型
                        const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
                        const url_path = "/PMS/PCM/CntM/CntMEdit?otype=view&id=" + u_cnt_phid; // 路径
                        $NG.open(`${protocol}//${url_domain}${url_path}`, { AppTitle: "合同信息" });
                        // }
                    }
                },
            });
        });
    }

    // 获取提前施工申请的信息
    function getAdConstructionOpp(params) {
        $NG.execServer("getAdConstructionOpp", { phid: mstform.getItem("u_opportunity_obj").getValue() }, function (res) {
            console.log("触发功能扩展:getAdConstructionOpp");
            if (res.count > 0) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                $NG.updateState((updater) => {
                    updater.data.p_form_equipment_list.setProps({
                        u_opportunity_obj_no: datas.u_opp_no,
                        u_bid_winning_date: datas.u_bid_dt,
                        u_cnt_u_opp_amt: datas.u_opp_amt,
                        u_winning_bid_amt: datas.u_bid_amt,
                        u_ad_total_amt: datas.u_ad_total_amt,
                        u_ad_material_amt: datas.u_ad_material_amt,
                        u_ad_engineering_amt: datas.u_ad_engineering_amt,
                        u_self_owned_cost: datas.u_self_owned_cost,
                        u_implement_cost: datas.u_implement_cost,
                    });
                });
            } else {
                console.log("功能扩展为空:getAdConstructionOpp");
            }
        });
    }
    // 获取项目信息
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            getSbqdCountByPhidPc();
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log("触发功能扩展:getPtInfoByPhid");
                const datas = JSON.parse(res.data)[0].extendObjects;
                $NG.updateState((updater) => {
                    //【注意这里的表名不能为控件ID，必须要是表名】
                    updater.data.p_form_equipment_list.setProps({
                        u_pc_no: datas.pc_no,
                        //售前顾问
                        u_sqgw: { value: datas.user_sqgw_phid, label: datas.user_sqgw_name },
                        //项目经理
                        u_project_manager: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //区域中心
                        u_regional_center: {
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        //项目类型
                        u_pc_type: { value: datas.type_phid, label: datas.type_name },
                    });
                });
            });
        }
    }
    // 获取合同信息
    function getCntMInfoByPhid(params) {
        cntDFilter();
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
            console.log("触发功能扩展:getCntMInfoByPhid");
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            $NG.updateState((updater) => {
                updater.data.p_form_equipment_list.setProps({
                    u_total_cnt_amt_vat: datas.cnt_sum_vat_fc,
                    u_cnt_no: { value: datas.pcm_phid, label: datas.pcm_no },
                    u_product_line: { value: datas.midwife_phid, label: datas.midwife_name },
                    u_cnt_type: { value: datas.pct_id, label: datas.pct_name },
                    u_customer: { value: datas.customer_id, label: datas.customer_name },
                    u_invoice_type: { value: datas.invoice_type_phid, label: datas.invoice_type_name },
                    u_init_cnt_amt: datas.cnt_sum_fc,
                });
            });
        });
    }
    // 合同过滤
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_list.u_cnt.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: $NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }
    //获取合同数量
    function getCntCount(table, key, fun, otherFun) {
        if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
        $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
            switch (res.count) {
                case 0:
                    return;
                case 1:
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    const temp_map = {};
                    temp_map[key] = datas.phid;
                    temp_map[`${key}_EXName`] = datas.bill_name;
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            ...temp_map,
                        });
                        setTimeout(() => {
                            fun();
                            if (otherFun) {
                                otherFun();
                            }
                        }, 200);
                    });
            }
        });
    }
    //设备清单数量
    function getSbqdCountByPhidPc() {
        let phidV = mstform.getValues().phid || 0;
        console.log("设备清单数量", phidV);
        $NG.execServer("getSbqdCountByPhidPc", { phid_pc: mstform.getItem("phid_pc").getValue(), phid: phidV }, (res) => {
            console.log("设备清单数量", res);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (_data.count > 0) {
                lock = false;
            } else {
                lock = true;
            }
        });
    }

    function dgrid1UpdateUI(params) {
        // 拟分包项分类过滤;
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell60"].u_sub_item_category.setProps({
                clientSqlFilter: `res_bs.resource_type='8570000000000002'`,
            });
        });
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell60"].u_sub_item.setProps({
                clientSqlFilter: `res_bs.resource_type='8570000000000002'`,
            });
        });

        // 拟采购项分类过滤;
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell61"].u_pur_item_category.setProps({
                clientSqlFilter: `res_bs.resource_type='2'`,
            });
        });
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell61"].u_pur_item.setProps({
                clientSqlFilter: `res_bs.resource_type='2'`,
            });
        });
        // 拟自制项分类过滤;
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell62"].u_self_item_category.setProps({
                clientSqlFilter: `res_bs.resource_type='8570000000000001'`,
            });
        });
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_equipment_list_d["Cell62"].u_self_item.setProps({
                clientSqlFilter: `res_bs.resource_type='8570000000000001'`,
            });
        });

        // 设置分组颜色
        $NG.updateUI((updater) => {
            if (updater.editGrid.p_form_equipment_list_d.Cell60) {
                updater.editGrid.p_form_equipment_list_d.Cell60.setProps({
                    headerStyle: {
                        backgroundColor: "#e5e5e5",
                    },
                });
            }
            if (updater.editGrid.p_form_equipment_list_d.Cell62) {
                updater.editGrid.p_form_equipment_list_d.Cell62.setProps({
                    headerStyle: {
                        backgroundColor: "#e5e5e5",
                    },
                });
            }
        });
        //按钮隐藏
        $NG.getCmpApi("toolbar_p_form_equipment_list_d").getItem("attachment").setHidden();
        const commonHideArray = ["u_cnt_prc_vat", "u_cnt_amt_vat"];
        commonHideArray.forEach((item) => {
            $NG.updateUI((updater) => {
                if (updater.editGrid.p_form_equipment_list_d[item]) {
                    updater.editGrid.p_form_equipment_list_d[item].setProps({
                        hidden: true, // 隐藏
                    });
                }
            });
        });

        const subHiddenArray = ["u_sub_no", "", "", "u_sub_invoice_type"];
        subHiddenArray.forEach((item) => {
            $NG.updateUI((updater) => {
                if (updater.editGrid.p_form_equipment_list_d["Cell60"][item]) {
                    updater.editGrid.p_form_equipment_list_d["Cell60"][item].setProps({
                        hidden: true, //隐藏
                    });
                }
            });
        });
        const purHiddenArray = ["u_pur_no", "", "", "u_pur_invoice_type"];
        purHiddenArray.forEach((item) => {
            $NG.updateUI((updater) => {
                if (updater.editGrid.p_form_equipment_list_d["Cell61"][item]) {
                    updater.editGrid.p_form_equipment_list_d["Cell61"][item].setProps({
                        hidden: true, //隐藏
                    });
                }
            });
        });
        const selfHiddenArray = ["u_self_no", "", "", "u_self_invoice_type"];
        selfHiddenArray.forEach((item) => {
            $NG.updateUI((updater) => {
                if (updater.editGrid.p_form_equipment_list_d["Cell62"][item]) {
                    updater.editGrid.p_form_equipment_list_d["Cell62"][item].setProps({
                        hidden: true, //隐藏
                    });
                }
            });
        });
    }

    function caculatedgrid1(items) {
        // console.log("caculatedgrid1", items);

        // items.u_state_EXName = "正常";
        if (!items.u_equipment_list_name) {
            items.u_equipment_list_name = items.u_cnt_item_EXName;
        }
        // 分包
        if (!items.u_sub_prc) {
            items.u_sub_prc = (items.u_sub_prc_vat || 0) / (1 + (items.u_sub_tax_rate || 0));
            items.u_sub_cost_vat = (items.u_sub_qty || 0) * (items.u_sub_prc_vat || 0);
            items.u_sub_cost = (items.u_sub_qty || 0) * (items.u_sub_prc || 0);
        }

        // 采购
        if (!items.u_pur_prc) {
            items.u_pur_prc = (items.u_pur_prc_vat || 0) / (1 + (items.u_pur_tax_rate || 0));
            items.u_pur_cost_vat = (items.u_pur_qty || 0) * (items.u_pur_prc_vat || 0);
            items.u_pur_cost = (items.u_pur_qty || 0) * (items.u_pur_prc || 0);
        }
        if (items.u_pur_qty) {
            items.u_rest_qty = items.u_pur_qty; // 将u_pur_qty的值赋给u_rest_qty
        } else {
            items.u_rest_qty = 0; // 将u_pur_qty的值赋给u_rest_qty
        }

        // 自制
        if (!items.u_self_prc) {
            items.u_self_prc = (items.u_self_prc_vat || 0) * (1 + (items.u_self_tax_rate || 0));
            items.u_self_cost_vat = (items.u_self_qty || 0) * (items.u_self_prc_vat || 0);
            items.u_self_cost = (items.u_self_qty || 0) * (items.u_self_prc || 0);
        }
        if (items.u_self_qty) {
            items.u_nzz_rest_qty = items.u_self_qty;
            items.u_nzzsysl = items.u_self_qty
        } else {
            items.u_nzz_rest_qty = 0;
            items.u_nzzsysl = 0
        }
    }
    // 明细监听单元格的函数
    function registerCalcGroup({ dataKey, qtyField, taxRate, prcField, prcVatField, amtField, amtVatField }) {
        console.log("registerCalcGroup", dataKey, qtyField, taxRate, prcField, prcVatField, amtField, amtVatField);
        let isCalculating = false;

        // 数量变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${qtyField}`);

        // 税率变动 计算未税单价和未税金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + (args[0][taxRate] || 0));
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);

            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${taxRate}`);

        // 未税单价变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            args[0][prcVatField] = (args[0][prcField] || 0) * (1 + (args[0][taxRate] || 0));
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);

            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${prcField}`);

        // 含税单价变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + (args[0][taxRate] || 0));
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);

            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${prcVatField}`);

        // 未税金额变动：反算单价
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            const qty = args[0][qtyField] || 0;
            args[0][prcField] = qty !== 0 ? args[0][amtField] / qty : 0;
            args[0][prcVatField] = (args[0][prcField] || 0) * (1 + (args[0][taxRate] || 0));
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${amtField}`);

        // 含税金额变化
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            const qty = args[0][qtyField] || 0;
            args[0][prcVatField] = qty !== 0 ? args[0][amtVatField] / qty : 0;
            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + (args[0][taxRate] || 0));
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${amtVatField}`);
    }

    function sumGridToForm() {
        let sum_cost_vat = 0;
        let sum_cost = 0;
        let sum_cnt_amt = 0;
        let sum_cnt_amt_vat = 0;
        let sum_sub_cost_vat = 0;
        let sum_sub_cost = 0;
        let sum_pur_cost_vat = 0;
        let sum_pur_cost = 0;
        let sum_self_cost_vat = 0;
        let sum_self_cost = 0;
        let sum_impl_cost_vat = 0; //实施费
        let sum_svc_cost_vat = 0; //服务成本
        let sum_sec_dev_amt = 0; //二次开发费
        let u_total_cnt_amt_vat = mstform.getItem("u_total_cnt_amt_vat").getValue(); //合同总额
        let u_win_bid_svc_amt = mstform.getItem("u_win_bid_svc_amt").getValue(); //中标服务费

        dgrid1.getData().forEach((items) => {
            sum_cnt_amt += parseFloat(items.u_cnt_amt) || 0; //清单合同未税金额
            sum_cnt_amt_vat += parseFloat(items.u_cnt_amt_vat) || 0; //清单合同含税金额
            sum_sub_cost_vat += parseFloat(items.u_sub_cost_vat) || 0; // 拟分包成本含税
            sum_sub_cost += parseFloat(items.u_sub_cost) || 0; // 拟分包成本未税
            sum_pur_cost_vat += parseFloat(items.u_pur_cost_vat) || 0; // 拟采购成本含税
            sum_pur_cost += parseFloat(items.u_pur_cost) || 0; // 拟采购成本未税
            sum_self_cost_vat += parseFloat(items.u_self_cost_vat) || 0; //拟自制成本含税
            sum_self_cost += parseFloat(items.u_self_cost) || 0; //拟自制成本未税
        });
        dgrid2.getData().forEach((items) => {
            sum_impl_cost_vat += parseFloat(items.u_total_impl_amt) || 0;
        });
        dgrid3.getData().forEach((items) => {
            sum_svc_cost_vat += parseFloat(items.u_total_svc_amt) || 0;
        });
        dgrid4.getData().forEach((items) => {
            sum_sec_dev_amt += parseFloat(items.u_rd_expenses) || 0;
        });

        sum_cost_vat = sum_sub_cost_vat + sum_pur_cost_vat + sum_self_cost_vat + sum_impl_cost_vat + sum_svc_cost_vat + sum_sec_dev_amt;
        sum_cost = sum_sub_cost + sum_pur_cost + sum_self_cost + sum_impl_cost_vat + sum_svc_cost_vat + sum_sec_dev_amt;

        $NG.updateState((updater) => {
            updater.data.p_form_equipment_list.setProps({
                u_cnt_amt: sum_cnt_amt,
                u_cnt_amt_vat: sum_cnt_amt_vat, //合同现额
                u_sub_cost: sum_sub_cost_vat, //拟分包含税
                u_sub_cost_amt: sum_sub_cost, //拟分包不含税
                u_pur_cost_vat: sum_pur_cost_vat, //拟采购成本含税
                u_pur_cost_amt: sum_pur_cost, //拟采购成本未税
                u_self_cost_vat: sum_self_cost_vat, //拟自制成本含税
                u_self_cost: sum_self_cost, //拟自制成本未税
                u_implement_amt: sum_impl_cost_vat,
                u_svc_cost_amt: sum_svc_cost_vat,
                u_sec_dev_amt: sum_sec_dev_amt,

                u_total_cost_amt: sum_cost, //总成本不含税
                u_total_cost_amt_vat: sum_cost_vat, //总成本含税
                u_revenue_cost_gm: sum_cnt_amt - sum_cost, //收入成本毛利
                u_signed_gm_rate: sum_cnt_amt !== 0 ? (sum_cnt_amt - sum_cost + sum_svc_cost_vat) / sum_cnt_amt : 0, //签单毛利率
                u_svc_amt_rate: sum_cnt_amt !== 0 ? u_win_bid_svc_amt / sum_cnt_amt : 0, //服务费率
                u_bid_gm_rate: sum_cnt_amt !== 0 ? (sum_cnt_amt - sum_cost - u_win_bid_svc_amt) / sum_cnt_amt : 0, //投标毛利率

                // 初始值赋值
                u_init_total_cost_amt: sum_cost,
                u_init_total_cost_amt_init: sum_cost_vat,
                u_init_revenue_cost_gm: sum_cnt_amt - sum_cost,
                u_init_signed_gm_rate: sum_cnt_amt !== 0 ? (sum_cnt_amt - sum_cost) / sum_cnt_amt : 0,

                u_sub_cost_ratio: sum_cost !== 0 ? sum_sub_cost / sum_cost : 0, //拟分包成本占比
                u_pur_cost_ratio: sum_cost !== 0 ? sum_pur_cost / sum_cost : 0, //拟采购成本占比
                u_self_cost_ratio: sum_cost !== 0 ? sum_self_cost / sum_cost : 0, //拟自制成本占比
                u_implement_cost_ratio: sum_cost !== 0 ? sum_impl_cost_vat / sum_cost : 0,
                u_svc_cost_ratio: sum_cost !== 0 ? sum_svc_cost_vat / sum_cost : 0,
                u_sec_dev_ratio: sum_cost !== 0 ? sum_sec_dev_amt / sum_cost : 0,
            });
        });
    }

    function insertClick() {
        var dgrid1 = $NG.getCmpApi("p_form_equipment_list_d");
        var orirow = dgrid1.getCheckedIndexes()[0] !== undefined ? dgrid1.getCheckedIndexes()[0] : dgrid1.getAllData().table.newRow.length;
        var maxrow = dgrid1.getAllData().table.newRow.length;
        dgrid1.addRows();
        setTimeout(function () {
            dgrid1.moveRow(maxrow, orirow + 1);
        }, 100); // 延迟 100 毫秒，视具体情况可以调整这个值
    }

    function cntDFilter() {
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_equipment_list_d.Cell142.u_cnt_item.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: {
                            pphid: $NG.getCmpApi("p_form_equipment_list").getItem("u_cnt").getValue() || 0,
                        },
                    },
                };
            })
        );
    }

    // 合同清单 唯一性检测
    async function detectUniqueContractList(details) {
        console.log("触发方法 detectUniqueContractList");

        duplicateMap.clear(); // 清空原有的 Map

        details.forEach((rec) => {
            const key = rec.u_cnt_item_no;
            if (key) {
                duplicateMap.set(key, (duplicateMap.get(key) || 0) + 1);
            }
        });
        // console.log("duplicateMap:", duplicateMap);
    }

    //根据 合同ID 获取 合同清单信息
    async function getCntDInfoByPhid(record, duplicateMap) {
        const res = await $NG.execServer("getCntDInfoByPhid", { cnd_id: mstform.getItem("u_cnt").getValue(), phid: record.u_cnt_item });
        // console.log("getCntDInfoByPhid:", res);
        if (res.count > 0) {
            const data = JSON.parse(res.data)[0].extendObjects;
            record.u_cnt_item_no = data.item_no; //合同清单编码
            record.u_spec = data.user_ggxh; //规格型号
            record.u_msunit = data.unit_phid;
            record.u_msunit_EXName = data.unit_name; //计量单位
            record.u_tech_params = data.user_jscs; //技术参数
            record.u_brand_name = data.brand_name; //品牌
            record.u_pc_subitem_category = data.user_gcfxfl; //工程分项分类
            // 判断：只有当该 item_no 只出现过一次才允许赋值数量等
            if (!duplicateMap.get(record.u_cnt_item_no)) {
                record.u_qty = data.qty; //数量
                record.u_cnt_item_tax_rate = data.taxrate; //税率
                record.u_cnt_prc_vat = data.prc_vat_fc; //含税单价
                record.u_cnt_prc = data.prc_fc; //未税单价
                record.u_cnt_amt_vat = data.amt_vat_fc; //含税金额
                record.u_cnt_amt = data.amt_fc; //未税金额
            } else {
                record.u_cnt_item_tax_rate = 0; //税率
                record.u_cnt_prc_vat = 0; //含税单价
                record.u_cnt_prc = 0; //未税单价
                record.u_cnt_amt_vat = 0; //含税金额
                record.u_cnt_amt = 0; //未税金额
            }
        }
        dgrid1.refreshView();
    }

    // 根据 合同编码 获取 合同清单信息
    function getCntDInfoByNo(record, duplicateMap) {
        console.log("触发方法 getCntDInfoByNo");

        if (mstform.getItem("u_cnt_no").getValue() && record.u_cnt_item_no && !record.u_state) {
            $NG.execServer("getCntDInfoByNo", { cnd_id: mstform.getItem("u_cnt").getValue(), item_no: "'" + record.u_cnt_item_no + "'" }, function (res) {
                // console.log("getCntDInfoByNo", res);
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    record.u_cnt_item = data.phid; //合同清单ID
                    record.u_cnt_item_EXName = data.item_name; //合同清单名称
                    record.u_model = data.user_ggxh; //规格型号
                    record.u_msunit = data.unit_phid; //计量单位
                    record.u_msunit_EXName = data.unit_name; //计量单位
                    record.u_tech_params = data.user_jscs; //技术参数
                    record.u_brand_name = data.brand_name; //品牌
                    record.u_pc_subitem_category = data.user_gcfxfl; //工程分项分类

                    // 判断是否第一次出现该 item_no
                    const itemNo = data.item_no;
                    if (!seenItemNo.has(itemNo)) {
                        seenItemNo.add(itemNo); // 标记已赋值
                        record.u_qty = data.qty;
                        record.u_cnt_item_tax_rate = data.taxrate;
                        record.u_cnt_prc = data.prc_fc;
                        record.u_cnt_prc_vat = data.prc_vat_fc;
                        record.u_cnt_amt = data.amt_fc;
                        record.u_cnt_amt_vat = data.amt_vat_fc;
                    } else {
                        record.u_cnt_item_tax_rate = 0;
                        record.u_cnt_prc = 0;
                        record.u_cnt_prc_vat = 0;
                        record.u_cnt_amt = 0;
                        record.u_cnt_amt_vat = 0;
                    }
                } else {
                    console.log("没有找到合同清单:getCntDInfoByNo");
                    record.u_cnt_item = null;
                    record.u_cnt_item_EXName = null;
                }
                dgrid1.refreshView();
            });
        }
    }

    //匹配物料请求
    async function getWlRequest(list) {
        const url = window.location.href;
        const protocol = $NG.split(url, "/")[0]; // 协议类型
        const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
        const url_path = "/sd/common/interior/createResourceFileSync"; // 路径
        const response = await fetch(`${protocol}//${url_domain}${url_path}`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json", // 设置请求头
            },
            body: JSON.stringify(list),
        });
        // const response = await fetch("https://inner-apisix.hisense.com/hisense/sd/common/interior/createResourceFileSync?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6 ", {
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json", // 设置请求头
        //   },
        //   body: JSON.stringify(list),
        // });
        const res = await response.json();
        if (res.IsOk) {
            //新增成功
            getItemData(null, false); //重新匹配
            $NG.message(`正在重新匹配`);
            $NG.alert("匹配完成,如有标准物料则跳过，请先到标准物料单匹配！");
        } else {
            if (res.data == "批量新增失败，入参为空！") {
                $NG.alert("匹配完成,如有标准物料则跳过，请先到标准物料单匹配！");
            } else {
                $NG.alert("匹配错误！");
            }
        }
    }

    function removeDuplicatesByKeys(arr) {
        const uniqueMap = new Map();
        for (const obj of arr) {
            //拟自制不准许发送或则分类
            if (obj.ResourceType == "8570000000000001" || obj.user_is_bz == 1) {
                continue;
            }
            delete obj.user_is_bz;
            // 生成一个由 ItemName、PhidResbs 和 PhidMsunit 组合而成的唯一键
            const key = `${obj.ItemName}-${obj.Spec}-${obj.PhidMsunit}`;
            if (!uniqueMap.has(key)) {
                // 如果该键还未存在于 Map 中，则将对象存入
                uniqueMap.set(key, obj);
            }
        }
        // 将 Map 中的值（即去重后的对象）提取到一个新数组中
        return Array.from(uniqueMap.values());
    }

    function getSubItemDataByPhid(items) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_sub_item }, function (res) {
            if (res.count > 0) {
                var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                items.u_sub_item_category = data.phid_resbs;
                items.u_sub_item_category_EXName = data.name;
                items.u_sub_name = data.itemname;
                items.u_sub_ggxh = data.spec;
                items.u_sub_item_msunit_EXName = data.msunit_name;
                items.u_sub_item_msunit = data.msunit_phid;
                items.u_sub_item_category = data.phid_resbs;
                items.u_sub_item_category_EXName = data.res_bs_name;
                items.u_fwgczdj = data.prc_ad;
                items.nfb_bz = data.user_is_bz;
            }
            dgrid1.refreshView();
        });
    }

    function getPurItemDataByPhid(items) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_pur_item }, function (res) {
            if (res.count > 0) {
                var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值
                items.u_pur_item_category = purdata.phid_resbs;
                items.u_pur_item_category_EXName = purdata.name;
                items.u_pur_name = purdata.itemname;
                items.u_pur_ggxh = purdata.spec;
                items.u_pur_item_msunit_EXName = purdata.msunit_name;
                items.u_pur_item_msunit = purdata.msunit_phid;
                items.u_pur_item_category = purdata.phid_resbs;
                items.u_pur_item_category_EXName = purdata.res_bs_name;
                items.u_cgzdj = purdata.prc_ad;
                items.ncg_bz = purdata.user_is_bz;
            }
        });
        $NG.execServer("getIsDj", { phid_wl: items.u_pur_item, phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            items.u_priced_prc = _data.u_target_prc;
            items.u_is_priced = 1;
        });
    }

    function getSelfItemDataByPhid(items) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_self_item }, function (res) {
            if (res.count > 0) {
                var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                items.u_self_item_category = data.phid_resbs;
                items.u_self_item_category_EXName = data.name;
                items.u_self_name = data.itemname;
                items.u_self_ggxh = data.spec;
                items.u_self_item_msunit = data.msunit_phid;
                items.u_self_item_msunit_EXName = data.msunit_name;
                items.u_self_item_category_EXName = data.res_bs_name;
                items.u_self_item_category = data.phid_resbs;
                items.u_zzzdj = data.prc_ad;
                items.nzz_bz = data.user_is_bz;
            }
        });
    }

    //onelock == 是否单条数据
    function getItemData(el, onelock = true) {
        function sum(items) {
            getItemDataByName(items);
        }
        if (onelock) {
            sum(el);
        } else {
            const arrs = dgrid1.getData();
            for (let i = 0; i < arrs.length; i++) {
                let items = arrs[i];
                sum(items);
            }
        }
    }

    function getItemDataByNo(items) {
        console.log(`触发方法:getItemDataByNo`);
        //3、根据导入的编码匹配拟分包项
        if (!items.u_sub_item && items.u_sub_no) {
            $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_sub_no + "'" }, function (res) {
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    items.u_sub_item = data.phid;
                    items.u_sub_item_EXName = data.itemno;
                    items.u_sub_name = data.itemname;
                    items.u_sub_item_category = data.phid_resbs;
                    items.u_sub_item_category_EXName = data.name;
                    items.u_sub_item_msunit_EXName = data.msunit_name;
                    items.u_sub_item_msunit = data.msunit_phid;
                    items.u_sub_ggxh = data.spec;
                    items.u_fwgczdj = data.prc_ad;
                }
            });
            items.u_sub_invoice_type = "8570000000000151";
            items.u_sub_invoice_type_EXName = "6%增值税专用发票";
            dgrid1.refreshView();
        }

        //3、匹配拟采购项目
        if (!items.u_pur_item && items.u_pur_no) {
            $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_pur_no + "'" }, function (res) {
                if (res.count > 0) {
                    var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值
                    items.u_pur_item = purdata.phid;
                    items.u_pur_item_EXName = purdata.itemno;
                    items.u_pur_name = purdata.itemname;
                    items.u_pur_item_category = purdata.phid_resbs;
                    items.u_pur_item_category_EXName = purdata.name;
                    items.u_pur_item_msunit = purdata.msunit_phid;
                    items.u_pur_item_msunit_EXName = purdata.msunit_name;
                    items.u_pur_ggxh = purdata.spec;
                    items.u_cgzdj = purdata.prc_ad;
                    $NG.execServer("getIsDj", { phid_wl: items.purdata.phid, phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
                        if (res.count == 0) return;
                        const _data = JSON.parse(res.data)[0].extendObjects;
                        items.u_priced_prc = _data.u_target_prc;
                        items.u_is_priced = 1;
                        dgrid1.refreshView();
                    });
                }
                dgrid1.refreshView();
            });
            items.u_pur_invoice_type = "8570000000000154";
            items.u_pur_invoice_type_EXName = "13%增值税专用发票";
            dgrid1.refreshView();
        }

        //4、匹配自制项目
        if (!items.u_self_item && items.u_self_no) {
            $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_self_no + "'" }, function (res) {
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    items.u_self_item = data.phid;
                    items.u_self_item_EXName = data.itemno;
                    items.u_self_name = data.itemname;
                    items.u_self_item_category = data.phid_resbs;
                    items.u_self_item_category_EXName = data.name;
                    items.u_self_ggxh = data.spec;
                    items.u_self_item_msunit = data.msunit_phid;
                    items.u_self_item_msunit_EXName = data.msunit_name;
                    items.u_zzzdj = data.prc_ad;
                }
                dgrid1.refreshView();
            });
        }
    }
    // 根据导入的名称+规格型号+计量单位匹配资源主文件
    async function getItemDataByName(items) {
        console.log("触发方法:getItemDataByName");
        // 拟分包
        if (String(items.u_sub_name || "").trim() && String(items.u_sub_item_msunit || "").trim() && String(items.u_sub_ggxh || "").trim()) {
            $NG.execServer("getItemDataByName", { itemname: `'${items.u_sub_name?.replace(/'/g, "''")}'`, spec: `'${items.u_sub_ggxh?.replace(/'/g, "''")}'`, msunit: items.u_sub_item_msunit }, function (res) {
                window.newNum++
                if (res.count > 0) {
                    let data = JSON.parse(res.data)[0].extendObjects; // 单返回值
                    items.u_sub_item = data.phid;
                    items.u_sub_item_EXName = data.itemno;
                    items.u_sub_item_category = data.phid_resbs;
                    items.u_sub_item_category_EXName = data.res_bs_name;
                    items.u_fwgczdj = data.prc_ad;
                    items.nfb_bz = data.user_is_bz;
                    dgrid1.refreshView();
                } else {
                    items.u_sub_item = "";
                    items.u_sub_item_EXName = "";
                    const _el = window.classData.filter((el) => el.phid == items.u_sub_item_category)[0];
                    console.log(`拟分包_el`, _el);
                    let bz = 0;
                    if (_el && Number(_el.user_is_bz) == 1) {
                        bz = 1;
                    }
                    window._list.push({
                        user_is_bz: bz,
                        ItemName: items.u_sub_name,
                        PhidResbs: items.u_sub_item_category,
                        PhidMsunit: items.u_sub_item_msunit,
                        Spec: items.u_sub_ggxh,
                        ResBsCode: items.u_sub_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                        ResourceType: "8570000000000002", // 假设资源类型是固定的
                    });
                    dgrid1.refreshView();
                }
            });
        }
        // 拟采购
        if (String(items.u_pur_name || "").trim() && String(items.u_pur_item_msunit || "").trim() && String(items.u_pur_ggxh || "").trim()) {
            $NG.execServer("getItemDataByName", { itemname: "'" + items.u_pur_name.replace(/'/g, "''") + "'", spec: "'" + items.u_pur_ggxh + "'", msunit: items.u_pur_item_msunit }, function (res) {
                window.newNum++
                if (res.count > 0) {
                    let data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    items.u_pur_item = data.phid;
                    items.u_pur_item_EXName = data.itemno;
                    items.u_pur_item_category = data.phid_resbs;
                    items.u_pur_item_category_EXName = data.res_bs_name;
                    items.u_cgzdj = data.prc_ad;
                    items.ncg_bz = data.user_is_bz;
                    dgrid1.refreshView();
                } else {
                    items.u_pur_item = "";
                    items.u_pur_item_EXName = "";
                    const _el = window.classData.filter((el) => el.phid == items.u_pur_item_category)[0];
                    let bz = 0;
                    if (_el && _el.user_is_bz == 1) {
                        bz = 1;
                    }
                    window._list.push({
                        user_is_bz: bz,
                        ItemName: items.u_pur_name,
                        PhidResbs: items.u_pur_item_category,
                        PhidMsunit: items.u_pur_item_msunit,
                        Spec: items.u_pur_ggxh,
                        ResBsCode: items.u_pur_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                        ResourceType: "2", // 假设资源类型是固定的
                    });
                    dgrid1.refreshView();
                }
            });
        }
        // 拟自主
        if (String(items.u_self_name || "").trim() && String(items.u_self_item_msunit || "").trim() && String(items.u_self_ggxh || "").trim()) {
            $NG.execServer("getItemDataByName", { itemname: "'" + items.u_self_name.replace(/'/g, "''") + "'", spec: "'" + items.u_self_ggxh + "'", msunit: items.u_self_item_msunit }, function (res) {
                window.newNum++
                if (res.count > 0) {
                    let data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    items.u_self_item = data.phid;
                    items.u_self_item_EXName = data.itemno;
                    items.u_self_item_category_EXName = data.res_bs_name;
                    items.u_self_item_category = data.phid_resbs;
                    items.u_zzzdj = data.prc_ad;
                    items.nzz_bz = data.user_is_bz;
                    dgrid1.refreshView();
                } else {
                    items.u_self_item = "";
                    items.u_self_item_EXName = "";
                    const _el = window.classData.filter((el) => el.phid == items.u_self_item_category)[0];
                    let bz = 0;
                    if (_el && _el.user_is_bz == 1) {
                        bz = 1;
                    }
                    // window._list.push({
                    //     user_is_bz: bz,
                    //     ItemName: items.u_self_name,
                    //     PhidResbs: items.u_self_item_category,
                    //     PhidMsunit: items.u_self_item_msunit,
                    //     Spec: items.u_self_ggxh,
                    //     ResBsCode: items.u_self_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                    //     ResourceType: "8570000000000001", // 假设资源类型是固定的
                    // });
                    dgrid1.refreshView();
                }
            });
        }
    }

    function useDataFun(k, t, v) {
        function saveData(k, v) {
            localStorage.setItem(k, JSON.stringify(v));
        }
        function getData(k) {
            const storedValue = localStorage.getItem(k);
            if (storedValue) {
                return JSON.parse(storedValue);
            }
            return null;
        }
        function clearData(k) {
            localStorage.removeItem(k);
        }
        function AsyncTypeData(k, t, v) {
            switch (t) {
                case "save":
                    saveData(k, v);
                    break;
                case "get":
                    return getData(k);
                    break;
                case "clear":
                    clearData(k);
                    break;
                default:
            }
        }
        AsyncTypeData(k, t, v);
    }

    async function danjvchaxun() {
        if (page.oType !== "add" && page.oType !== "edit") return;
        await dgrid2.clearRows();
        await dgrid3.clearRows();
        await dgrid4.clearRows();
        if (dgrid2) {
            await $NG.execServer("get_impl_cost_budget_info", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log(`实施费请求`, res);
                if (res.count == 0) return;
                const data = JSON.parse(res.data);
                //默认增行,批量新增表体数据
                var gridArr = []; //定义表体数组
                var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                for (var i = 0; i < gridCount; i++) {
                    var gridObj = {};
                    //对表体字段进行赋值,可以取数据库中的值进行赋值
                    gridObj.u_bill_no = data[i].extendObjects.bill_no;
                    gridObj.u_total_impl_amt = data[i].extendObjects.u_total_impl_amt;
                    gridObj.u_total_impl_labor_amt = data[i].extendObjects.u_total_impl_labor_amt;
                    gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                    gridObj.u_total_sec_dev_amt = data[i].extendObjects.u_total_sec_dev_amt;
                    gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                    gridObj.u_source_phid = data[i].extendObjects.phid;
                    gridArr.push(gridObj);
                    if (data[i].extendObjects.app_status != 1) {
                        window._lsz_catch_status["impl"].push(data[i].extendObjects.bill_no);
                    }
                }
                //调用新增表体行数据的函数
                dgrid2.addRows(gridArr);
            });
        }
        if (dgrid3) {
            await $NG.execServer("get_svc_cost_budget_info", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log(`服务请求`, res);
                if (res.count == 0) return;
                const data = JSON.parse(res.data);
                //默认增行,批量新增表体数据
                var gridArr = []; //定义表体数组
                var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                for (var i = 0; i < gridCount; i++) {
                    //对表体字段进行赋值,可以取数据库中的值进行赋值
                    var gridObj = {};
                    gridObj.u_bill_no = data[i].extendObjects.bill_no;
                    gridObj.u_total_svc_amt = data[i].extendObjects.u_total_svc_amt;
                    gridObj.u_total_svc_labor_amt = data[i].extendObjects.u_total_svc_labor_amt;
                    gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                    gridObj.u_source_phid = data[i].extendObjects.phid;
                    // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                    gridArr.push(gridObj);
                    if (data[i].extendObjects.app_status != 1) {
                        window._lsz_catch_status["svc"].push(data[i].extendObjects.bill_no);
                    }
                }
                //调用新增表体行数据的函数
                dgrid3.addRows(gridArr);
            });
        }
        if (dgrid4) {
            await $NG.execServer("getDevCostBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log(`研发费请求`, res);
                if (res.count == 0) return;
                const data = JSON.parse(res.data);
                //默认增行,批量新增表体数据
                var gridArr = []; //定义表体数组
                var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                for (var i = 0; i < gridCount; i++) {
                    //对表体字段进行赋值,可以取数据库中的值进行赋值
                    var gridObj = {};
                    gridObj.u_bill_no = data[i].extendObjects.bill_no;
                    gridObj.u_rdrg_expenses_total = data[i].extendObjects.u_total_labor_amt;
                    gridObj.u_rcfy_total = data[i].extendObjects.u_total_daily_amt;
                    gridObj.u_rd_expenses = data[i].extendObjects.u_total_dev_amt;
                    gridObj.u_source_phid = data[i].extendObjects.phid;
                    // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                    gridArr.push(gridObj);
                    if (data[i].extendObjects.app_status != 1) {
                        window._lsz_catch_status["rd"].push(data[i].extendObjects.bill_no);
                    }
                }
                //调用新增表体行数据的函数
                dgrid4.addRows(gridArr);
            });
        }
    }
    function checkImpdataStatus() {
        // 每次执行时，重置 _lsz_catch_status
        window._lsz_catch_status = {
            impl: [],
            svc: [],
            rd: [],
        };

        console.log("是否审核----", window._lsz_catch_status);
        let result = {
            valid: true, // 默认没有未审核单据
            message: "", // 默认没有提示信息
        };

        // 确保 window._lsz_catch_status 已定义并且是一个对象
        if (window._lsz_catch_status && typeof window._lsz_catch_status === "object") {
            // 检查所有的数组是否都为空
            for (let key in window._lsz_catch_status) {
                if (Array.isArray(window._lsz_catch_status[key]) && window._lsz_catch_status[key].length > 0) {
                    result.valid = false; // 存在未审核单据
                    break; // 找到一个非空数组就可以结束检查
                }
            }

            if (!result.valid) {
                // 如果有非空数组，继续你的逻辑
                let title = "预算费用包含未审核明细：";
                const expenseTypes = {
                    impl: "实施费用预算编码",
                    svc: "服务费用预算编码",
                    rd: "二开费用预算编码",
                };

                // 拼接每个费用类型的提示信息
                for (let key in window._lsz_catch_status) {
                    if (expenseTypes[key] && Array.isArray(window._lsz_catch_status[key]) && window._lsz_catch_status[key].length > 0) {
                        let expenseDetail = window._lsz_catch_status[key].map((item) => `${expenseTypes[key]}：${item}`).join("、");
                        title += expenseDetail;
                    }
                }

                // 弹窗提示
                $NG.alert(title);
                result.message = title; // 保存提示信息
            }
        } else {
            console.error("window._lsz_catch_status 未定义或格式不正确");
        }

        return result;
    }

    getUserIsBz();
    function getUserIsBz() {
        $NG.execServer("getUserIsBz", {}, (res) => {
            window.classData = JSON.parse(res.data).reduce((value, item) => {
                value.push(item.extendObjects);
                return value;
            }, []);
        });
    }

    ////////////////////////////////////////////////////////////////// START \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    /**
     * 将标准物料推送到标准物料申请单 ，此处已封装
     * @Param arr 这个是明细全数据
     * @Param keys 这个要按顺序写数组[物料主键，物料名称，单位，规格，分类],如果一条明细多个物料，请写成二维数组，顺序不变
     * @Param boolkey 这个是代表标准物料的字段名称 ,规格keys是二维数组，那么keys必须是数组，且顺序分别是二维数组对应物料的标准字段
     */
    // 下推标准物料逻辑
    async function ToWlApply(arr, keys, boolkey) {

        const paramsObj = {};
        const queryString = location.href.split("?")[1];
        const paramPairs = queryString.split("&");
        paramPairs.forEach((paramPair) => {
            const [key, value] = paramPair.split("=");
            const decodedValue = decodeURIComponent(value);
            paramsObj[key] = decodedValue;
        });
        $NG.execServer("getUserIsBz", {}, (res) => {
            const _data = JSON.parse(res.data);
            const classData = _data.reduce((value, item) => {
                value.push(item.extendObjects);
                return value;
            }, []);
            let all = [];
            //判断是否是二维数组
            if (keys[0] instanceof Array) {
                keys.forEach((item1, index1) => {
                    const temp = arr.reduce((value, item) => {
                        let _el = classData.filter((it) => it.phid == item[item1[4]])[0];
                        if (!item[item1[0]] && _el && _el.user_is_bz == 1) {
                            value.push({
                                itemname: item[item1[1]],
                                msunit: item[item1[2]],
                                msunit_EXName: item[item1[2] + "_EXName"],
                                spec: item[item1[3]],
                                category: item[item1[4]],
                                category_EXName: item[item1[4] + "_EXName"],
                                source: item["phid"],
                                tableName: paramsObj.AppTitle.split("-")[0],
                                bz: item[boolkey[index1]],
                            });
                        }
                        return value;
                    }, []);
                    all = [...all, ...temp];
                });
            } else {
                const temp = arr.reduce((value, item) => {
                    let _el = classData.filter((it) => it.phid == item[keys[4]])[0];
                    if (!item[keys[0]] && _el && _el.user_is_bz == 1) {
                        value.push({
                            itemname: item[keys[1]],
                            msunit: item[keys[2]],
                            msunit_EXName: item[keys[2] + "_EXName"],
                            spec: item[keys[3]],
                            category: item[keys[4]],
                            category_EXName: item[keys[4] + "_EXName"],
                            source: item["phid"],
                            tableName: paramsObj.AppTitle.split("-")[0],
                            bz: item[boolkey],
                        });
                    }
                    return value;
                }, []);
                all = temp;
            }
            all = all.filter((el) => {
                if (el.itemname && el.msunit && el.spec && el.category) {
                    return true;
                } else {
                    return false;
                }
            });
            const data = {
                data: all,
                time: new Date().getTime(),
            };
            const user = $NG.getUser();
            // 设置本地存储
            localStorage.setItem("material_apply_data", JSON.stringify(data));
            // 跳转到标准物料申请单
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = `/react/index.html#/customform/detail?otype=add&busType=EFORM9000000207&isSso=1&AppTitle=标准物料申请单-新增&treeOcode=${user.orgID}&treeOcodeName=${user.orgName}&status=ToMaterial&treePc=&treePcName=`; // 路径
            $NG.open(`${protocol}//${url_domain}${url_path}`);
        });
    }

    //   // 下推自主产品ERP
    //   async function toERPitemName(){
    //     // 获取勾选的明细
    //     const checkedRow = dgrid1.getData().reduce((value,item)=>{
    //         if(item.checked){
    //             value.push({...item})
    //         }
    //         return value
    //     },[])
    //     // 非自主软件8570000000000058  自主软件8570000000000059
    //     // 判断是否包含软件类型
    //     const noAppType = checkedRow.reduce((value,item)=>{
    //         if(![8570000000000058,8570000000000059].includes(item.u_revenue_type)){
    //             value.push({...item})
    //         }
    //         return value
    //     },[])
    //     // 处理数据结构
    //     const data = {
    //         time:new Date().getTime(),
    //         timeout:15 * 1000,
    //         data:noAppType
    //     }
    //     // 拼接url
    //     // 跳转到标准物料申请单
    //     const user = $NG.getUser()
    //     const url = window.location.href;
    //     const protocol = $NG.split(url, "/")[0]; // 协议类型
    //     const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
    //     const url_path = `/react/index.html#/customform/detail?otype=add&busType=EFORM9000000084&isSso=0&AppTitle=自主产品ERP出库申请-新增&schemeId=8570000000000160&treeOcode=${user.orgID}&treeOcodeName=${user.orgName}&status=To&menucode=8f2cd738-55dd-4cc4-bdae-9528e4db384a`; // 路径
    //     const toUrl = `${protocol}//${url_domain}${url_path}`
    //     if(noAppType.length != checkedRow.length){
    //         const toLock = await $NG.confirm('选中数据包含收入类型为 “软件收入” 的明细，继续下推将自动过滤掉相关明细，反之则手动修改！')
    //         if(toLock){
    //             data.time = new Date().getTime()
    //             window.localStorage.setItem("erpData",JSON.stringify(data))
    //             $NG.open(toUrl)
    //         } 
    //     } else {
    //         data.time = new Date().getTime()
    //         window.localStorage.setItem("erpData",JSON.stringify(data))
    //         $NG.open(toUrl)
    //     }
    //   }

    // 判断设备清单有没有变更
    getSbqdIsChg();
    function getSbqdIsChg() {
        const source_phid = mstform.getValues().phid;
        if (!source_phid) return;
        $NG.execServer("getSbqdIsChg", { source_phid }, (res) => {
            const _data = JSON.parse(res.data)[0].extendObjects;
            console.log(_data, source_phid);
            if (_data.count !== 0) {
                $NG.alert("当前设备清单存在变更，已显示部分初始金额！");
                const arrkey = ["u_init_cnt_amt", "u_init_revenue_cost_gm", "u_init_signed_gm_rate", "u_init_total_cost_amt"];
                arrkey.forEach((item) => {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_equipment_list[item].setProps({
                            hidden: false,
                        });
                    });
                });
            }
        });
    }

    // 自动生产编码 ** 如果想复用，请在全局文件中定义一个 变量：let maxNo=null
    ts();
    function ts() {
        $NG.execServer("autoSbqdno", { num: formatDate(new Date(), "YYYYmmDD") }, function (res) {
            if (res.count !== 0) {
                const _data = JSON.parse(res.data)[0].extendObjects;
                console.log(`最大编号`, _data);
                maxNo = Number(_data.u_equipment_list_no);
            } else {
                maxNo = Number(formatDate(new Date(), "YYYYmmDD") + "000000");
            }
        });
    }
    function autoCreateNo(int) {
        let str = String(maxNo).slice(-6);
        let num = Number(str) + int;
        const s = formatDate(new Date(), "YYYYmmDD") + String(num).padStart(6, "0");
        return s;
    }
    // 日期格式化
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            case "YYYYmmDD":
                formattedDate = `${year}${month.padStart(2, "0")}${day.padStart(2, "0")}`;
                break;
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }

    // 跳转到定价申请
    function openDJ() {
        try {
            console.log(`openDJ`);
            var mstform = $NG.getCmpApi("p_form_equipment_list");
            const dgrid1 = $NG.getCmpApi("p_form_equipment_list_d");
            const selectedData = dgrid1.getSelectedData();
            if (selectedData && selectedData.length > 0) {
                // 提取 u_source_id 和 u_source_table
                // console.log(`selectedData`, selectedData);
                // console.log(`是否已定价`, selectedData[0].u_is_priced);
                const extractedData = selectedData.map((item) => ({
                    phid_pc: mstform.getItem("phid_pc").getValue(),
                    phid_pc_name: mstform.getValues().phid_pc_EXName,
                    u_status: selectedData[0].u_is_priced ? "定价完成" : "待定价",
                }));

                localStorage.removeItem("localStorageEQ");
                // console.log("localStorageEQ 已清除");

                localStorage.setItem("localStorageEQ", JSON.stringify(extractedData));
                // console.log("已存入 localStorageEQ :", extractedData);
            } else {
                console.log("没有选中的数据");
            }
            document.removeEventListener("dblclick", handleDblClick);
            document.addEventListener("dblclick", handleDblClick);
        } catch (e) { }
    }

    // 双击事件
    function handleDblClick(event) {
        const location_url = window.location.href;
        const protocol = $NG.split(location_url, "/")[0]; // 协议类型
        const url_domain = $NG.split(location_url, "/")[2]; // 直接提取域名部分
        const baseUrl = `${protocol}//${url_domain}/react/index.html`;
        const queryParams = {
            id: "8570000000000001",
            otype: "view",
            busType: "EFORM9000000201",
            isSso: "1",
            AppTitle: "定价需求池",
        }; // 构造查询字符串
        const queryString = new URLSearchParams(queryParams).toString();
        const url = `${baseUrl}#/customform/detail?${queryString}`; // 打开URL // $NG.open(url, { AppTitle: "定价需求池" });
        const target = event.target.closest('[data-key="u_priced_prc"]');
        if (!target) return; // 避免 `null` 问题

        $NG.confirm("是否跳转到定价结果？").then((result) => {
            if (result) {
                $NG.open(url, { AppTitle: "定价需求池" });
            }
        });
    }

    // function checkImpdataStatus() {
    //   console.log("是否审核----", window._lsz_catch_status);
    //   // 检查 window._lsz_catch_status 是否为空
    //   if (window._lsz_catch_status) {
    //     // 检查所有的数组是否都为空
    //     for (let key in window._lsz_catch_status) {
    //       if (Array.isArray(window._lsz_catch_status[key]) && window._lsz_catch_status[key].length > 0) {
    //         checkImpFlg = false;
    //         break; // 找到一个非空数组就可以结束检查
    //       } else {
    //         checkImpFlg = true;
    //       }
    //     }
    //     if (!checkImpFlg) {
    //       // 如果有非空数组，继续你的逻辑
    //       let title = "预算费用包含未审核明细：";
    //       const expenseTypes = {
    //         impl: "实施费用预算编码",
    //         svc: "服务费用预算编码",
    //         rd: "二开费用预算编码",
    //       };
    //       for (let key in window._lsz_catch_status) {
    //         if (expenseTypes[key]) {
    //           window._lsz_catch_status[key].forEach((item, index) => {
    //             title += `${expenseTypes[key]}：${item}${index === window._lsz_catch_status[key].length - 1 ? "" : "、"}`;
    //           });
    //         }
    //       }
    //       $NG.alert(title);
    //     }
    //   } else {
    //     checkImpFlg = true;
    //   }
    // }
});
